package com.example.demo.service.impl;

import com.example.demo.dto.ApiResponse;
import com.example.demo.entity.*;
import com.example.demo.repository.ReservationRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.ReservationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
@RequiredArgsConstructor
public class ReservationServiceImpl implements ReservationService {

    private final ReservationRepository reservationRepository;
    private final UserRepository userRepository;

    @Override
    public ApiResponse<?> createReservation(Long userId, Reservation reservation) {
        return userRepository.findById(userId)
                .map(user -> {
                    if (reservation.getLab() == null) {
                        return ApiResponse.error("实验室不能为空");
                    }
                    if (reservation.getStartTime() == null) {
                        return ApiResponse.error("开始时间不能为空");
                    }
                    if (reservation.getEndTime() == null) {
                        return ApiResponse.error("结束时间不能为空");
                    }
                    if (reservation.getStartTime().isAfter(reservation.getEndTime())) {
                        return ApiResponse.error("开始时间不能晚于结束时间");
                    }
                    if (reservation.getStartTime().isBefore(LocalDateTime.now())) {
                        return ApiResponse.error("不能预约过去的时间");
                    }

                    reservation.setUser(user);
                    reservation.setStatus(ReservationStatus.PENDING);
                    return ApiResponse.success("预约创建成功", reservationRepository.save(reservation));
                })
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public ApiResponse<?> updateReservation(Reservation reservation) {
        if (reservation.getId() == null) {
            return ApiResponse.error("预约ID不能为空");
        }
        return reservationRepository.findById(reservation.getId())
                .map(existingReservation -> {
                    if (reservation.getStartTime() != null) existingReservation.setStartTime(reservation.getStartTime());
                    if (reservation.getEndTime() != null) existingReservation.setEndTime(reservation.getEndTime());
                    if (reservation.getPurpose() != null) existingReservation.setPurpose(reservation.getPurpose());
                    if (reservation.getParticipants() != null) existingReservation.setParticipants(reservation.getParticipants());
                    
                    return ApiResponse.success("预约更新成功", reservationRepository.save(existingReservation));
                })
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> deleteReservation(Long id) {
        return reservationRepository.findById(id)
                .map(reservation -> {
                    reservationRepository.delete(reservation);
                    return ApiResponse.success("预约删除成功", null);
                })
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> getReservationById(Long id) {
        return reservationRepository.findById(id)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> getReservationsByStudent(User student) {
        return ApiResponse.success(reservationRepository.findByUser(student));
    }

    @Override
    public ApiResponse<?> getReservationsByStatus(ReservationStatus status) {
        return ApiResponse.success(reservationRepository.findByStatus(status));
    }

    @Override
    public ApiResponse<?> getReservationsByApprover(User approver) {
        return ApiResponse.success(reservationRepository.findByApprover(approver));
    }

    @Override
    public ApiResponse<?> getReservationsByDateRange(LocalDateTime start, LocalDateTime end) {
        return ApiResponse.success(reservationRepository.findByStartTimeBetween(start, end));
    }

    @Override
    public ApiResponse<?> approveReservation(Long id) {
        return reservationRepository.findById(id)
                .map(reservation -> {
                    if (reservation.getStatus() != ReservationStatus.PENDING) {
                        return ApiResponse.error("只能审批待处理的预约");
                    }
                    reservation.setStatus(ReservationStatus.APPROVED);
                    return ApiResponse.success("预约审批通过", reservationRepository.save(reservation));
                })
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> rejectReservation(Long id) {
        return reservationRepository.findById(id)
                .map(reservation -> {
                    if (reservation.getStatus() != ReservationStatus.PENDING) {
                        return ApiResponse.error("只能拒绝待处理的预约");
                    }
                    reservation.setStatus(ReservationStatus.REJECTED);
                    return ApiResponse.success("预约已拒绝", reservationRepository.save(reservation));
                })
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> cancelReservation(Long id) {
        return reservationRepository.findById(id)
                .map(reservation -> {
                    if (reservation.getStatus() == ReservationStatus.CANCELLED) {
                        return ApiResponse.error("预约已经取消");
                    }
                    if (reservation.getStatus() == ReservationStatus.COMPLETED) {
                        return ApiResponse.error("已完成的预约不能取消");
                    }
                    reservation.setStatus(ReservationStatus.CANCELLED);
                    return ApiResponse.success("预约取消成功", reservationRepository.save(reservation));
                })
                .orElse(ApiResponse.error("预约不存在"));
    }

    @Override
    public ApiResponse<?> getUserReservations(Long userId) {
        return userRepository.findById(userId)
                .map(user -> ApiResponse.success(reservationRepository.findByUser(user)))
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public ApiResponse<?> getLabReservations(Long labId) {
        return ApiResponse.success(reservationRepository.findByLabId(labId));
    }
} 